import type { Router } from 'vue-router';
import NProgress from 'nprogress';

import usePermission from '@/hooks/usePermission';
import { useUserStore } from '@/store';
import { appRoutes } from '../routes';
import { NOT_FOUND } from '../constants';
import { formatDynamicRoutes, addDynamicRoutes } from '@/utils/dynamic-routes';

export default function setupPermissionGuard(router: Router) {
  router.beforeEach(async (to, _from, next) => {
    const userStore = useUserStore();
    const Permission = usePermission();

    // ====== 新增：每次刷新都注册动态路由 ======
    if (userStore.menus && userStore.menus.length > 0) {
      const exist = router.getRoutes().some(r => r.path === to.path);
      if (!exist) {
        const dynamicRoutes = formatDynamicRoutes(userStore.menus);
        addDynamicRoutes(dynamicRoutes);
        next({ ...to, replace: true });
        return;
      }
    }

    // ====== 新增：刷新时自动恢复用户信息 ======
    if (!userStore.role) {
      userStore.restoreFromLocal();
    }

    try {
      // 如果有用户角色但没有menus，获取动态菜单
      if (userStore.role && !userStore.menus) {
        try {
          // 获取功能菜单列表
          const menus = await userStore.getFuncMenus();

          if (menus && (Array.isArray(menus) ? menus.length > 0 : true)) {
            // 格式化并添加动态路由
            const dynamicRoutes = formatDynamicRoutes(menus);
            addDynamicRoutes(dynamicRoutes);

            // 重新导航到目标路由
            next({ ...to, replace: true });
            return;
          }
        } catch (error) {
          console.error('Failed to get menus:', error);
          // 如果获取菜单失败，继续正常流程
        }
      }

      // 判断路由权限
      const permissionsAllow = Permission.accessRouter(to);

      // 检查是否匹配到了404路由
      const isMatchedToNotFound = to.matched.some(route => route.name === 'notFound');
      if (isMatchedToNotFound) {

        // 检查是否有对应的动态路由
        const dynamicRoute = router.getRoutes().find(route => route.path === to.path && route.name !== 'notFound');
        if (dynamicRoute) {
          next({ name: dynamicRoute.name, replace: true });
          return;
        }
      }

      if (permissionsAllow) {
        next();
      } else {
        // 如果有动态路由，尝试在动态路由中找到第一个有权限的路由
        if (userStore.menus && userStore.menus.length > 0) {
          try {
            const dynamicRoutes = formatDynamicRoutes(userStore.menus);
            const destination = Permission.findFirstPermissionRoute(dynamicRoutes, userStore.role) || NOT_FOUND;
            next(destination);
          } catch (error) {
            console.error('Failed to find permission route:', error);
            next(NOT_FOUND);
          }
        } else {
          // 否则，尝试在静态路由中找到第一个有权限的路由
          try {
            const destination = Permission.findFirstPermissionRoute(appRoutes, userStore.role) || NOT_FOUND;
            next(destination);
          } catch (error) {
            console.error('Failed to find static route:', error);
            next(NOT_FOUND);
          }
        }
      }
    } catch (error) {
      console.error('Permission guard error:', error);
      next(NOT_FOUND);
    } finally {
      NProgress.done();
    }
  });
}
